<template>
    <div class="wh-100" style="background-color: white">
        <div style="height: 60px" class="w-100  bor-base-b  pl-24 fw-6 fs-18 d-flex d-flex-between-center">
            <div>生源信息查询</div>
            <div class="d-flex">
                <el-button type="text" size="small" @click="downloadTemple">下载模板</el-button>
                <el-upload accept=".xls, .xlsx,.dbf,.zip,.rar" :before-upload="handleUpload">
                    <el-button type="primary" size="small" class="ml-12">导入生源信息</el-button>
                </el-upload>
            </div>
        </div>
        <div class="h-80 bor-base-b">
            <div class="h-10 bor-base-b d-flex-between-center">
                <div class="py-12 pl-24 d-flex-center mr-auto">
                    <!--                    <el-checkbox v-model="checked" style="margin-left: 10px; margin-right: 20px" @change="toggleAllSelection"></el-checkbox>-->
                    <Button style="background-color: white" @click="deleteInBatches">批量删除</Button>
                    <Button type="dashed" @click="changeTip">{{ openTip ? '关闭提示' : '开启提示' }}</Button>

                </div>
                <div class="pl-100 d-flex-align-center  w-50">
                        <Select  class="w-20 ml-auto" v-model="pageParams.year" clearable placeholder="请选择年份">
                            <Option v-for="item in aGivenYearSelect" :key="item.year" :value="item.year"> {{item.year}}</Option>
                        </Select>
                        <Input
                            class="w-60 ml-8"
                            placeholder="按表名称查找"
                            @on-keyup="pageParams.search=pageParams.search.replace(/\s/g,'')"
                            v-model="pageParams.search"
                        ></Input>
                        <Button style="background-color: #1890ff; color: white" class="mr-8" @click="toSearch">搜索</Button>
                </div>
            </div>
            <div class="h-90 overflow-auto">
                <Alert v-show="openTip" show-icon>
                    已选择
                    <span >{{ selectList.length }}</span>
                    项
                    <a @click="toggleSelection">清空</a>
                </Alert>
                <el-table
                    v-loading="loading"
                    :height="heightNmber"
                    width="100%"
                    ref="formRef"
                    empty-text="暂无数据"
                    :header-cell-style="{ background: $backColor, color: '#333333' }"
                    :data="tableData"
                    style="width: 100%"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column v-for="column in tableColumns" :key="column.prop" :prop="column.prop" :label="column.label"></el-table-column>
                    <el-table-column prop="state" label="操作" fixed="right">
                        <template #default="scope">
                            <el-button type="text" size="small" @click="toDeails(scope.row.id)">查看</el-button>
                            <el-button type="text" size="small" @click="toDelete(scope.row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="h-10 d-flex d-flex-center fs-14">
            <Page show-total :total="pageTotal" :current="pageParams.pageNumber" :page-size="pageParams.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" show-sizer show-elevator />
        </div>
    </div>
</template>
<script>
import { addExcelAPI, delByIdAPI, getByYearAndNameAPI, queryTheYearDropDownBoxAPI, delByIdsAPI } from '../../../api/bys/recruitmentManagement';
import { getAllDictList } from '../../../api';

export default {
    data() {
        return {
            checked: false,
            selectedRows: [], // 用于保存选择的行
            importForm: {
                file: null
            },
            aGivenYearSelect: [
                { title: '2021年', value: '1' },
                { title: '2022年', value: '2' },
                { title: '2023年', value: '3' }
            ],
            loading: false,
            modelPosition: '',
            tableData: [],
            tableColumns: [
                { prop: 'year', label: '年份' },
                { prop: 'infoTableName', label: '名称' },
                { prop: 'updateTime', label: '更新时间' }
            ],
            pageTotal: 0,
            pageParams: {
                year: '', //年份
                search: '', //名称
                pageSize: 10,
                pageNumber: 1
            },
            heightNmber:'95%',
            openTip:true,
            selectList:[],
        };
    },
    mounted() {
        this.postData();
    },
    methods: {
        changeTip(){
            this.openTip = !this.openTip
            if(this.openTip){
                this.heightNmber='95%'
            }else{
                this.heightNmber='100%'
            }
        },
        toggleSelection() {
            this.$refs.formRef.clearSelection();
        },
        postData: function() {
            getByYearAndNameAPI(this.pageParams).then(res => {
                console.log(res.result);
                this.tableData = res.result;
                this.getTheYear();
            });
        },
        //当选项改变时，保存选择的行
        handleSelectionChange(selectedRows) {
            this.selectedRows = selectedRows;
            this.selectList=selectedRows
            this.checked = selectedRows.length === this.tableData.length;
        },
        //下载模板
        downloadTemple() {
            window.location.href = process.env.BASE_URL + 'xxxx年河南省生源信息查询统计表.xlsx';
        },
        //导入
        handleUpload(file) {
            const fileExt = file.name
                .split('.')
                .pop()
                .toLocaleLowerCase();
            if (!(fileExt == 'xlsx' || fileExt == 'xls')) {
                this.$Notice.warning({
                    title: '文件类型错误',
                    desc: "所选文件'" + file.name + "'不是EXCEL文件，请选择后缀为.xlsx或者.xls的文件"
                });
            } else {
                this.importForm.file = file;
                this.exportMessage();
            }
            return false;
        },
        deleteInBatches() {
            const ids = this.selectedRows.map(row => row.id);
            delByIdsAPI({ ids: ids }).then(res => {
                console.log(res.message);
                this.$message.success(res.message);
                this.postData();
            });
        },
        //全选
        toggleAllSelection() {
            if (this.checked) {
                this.$refs.formRef.toggleAllSelection();
            } else {
                this.$refs.formRef.clearSelection();
            }
        },
        //获取年份
        getTheYear() {
            queryTheYearDropDownBoxAPI().then(res => {
                console.log(res.result);
                this.aGivenYearSelect = Array.from(new Set(res.result));
                console.log(this.aGivenYearSelect);
            });
        },
        //导入信息
        async exportMessage() {
            let formData = new FormData();
            formData.append('file', this.importForm.file);
            addExcelAPI(formData).then(res => {
                if (res.code === 200) {
                    this.$message.success(res.message);
                    this.postData();
                } else if (res.code === 201) {
                    this.$message.success(res.message);
                    this.postData();
                    const byteArray = Uint8Array.from(atob(res.result), c => c.charCodeAt(0));
                    const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                    // 创建临时 URL 对象
                    const url = URL.createObjectURL(blob);
                    const downloadLink = document.createElement('a');
                    downloadLink.href = url;
                    downloadLink.download = '导入失败数据汇总.xlsx'; // 设置文件名
                    downloadLink.click();
                } else {
                    this.$Message.error(res.message);
                    const byteArray = Uint8Array.from(atob(res.result), c => c.charCodeAt(0));
                    const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                    // 创建临时 URL 对象
                    const url = URL.createObjectURL(blob);
                    const downloadLink = document.createElement('a');
                    downloadLink.href = url;
                    downloadLink.download = '导入失败数据汇总.xlsx'; // 设置文件名
                    downloadLink.click();
                }
            });
        },
        toDelete(id) {
            delByIdAPI({ id: id }).then(res => {
                console.log(res.message);
                this.postData();
            });
        },
        changePage: function(val) {
            this.pageParams.pageNumber = val;
            this.postData();
        },
        // region TODO 查看详情跳转
        toDeails(id) {
            console.log(id);
            this.$router.push({ name: 'DetailsOfStudentOrigin', query: { id: id } });
        },
        // endregion
        // region TODO 搜索
        toSearch() {
            this.postData();
        },
        // endregion
        changePageSize: function(val) {
            this.pageParams.pageSize = val;
            this.postData();
        }
    }
};
</script>
